package com.fang.algorithm;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author fanglingxiao
 * @version 1.0
 * @description TODO
 * @date 2022/8/1 2:37 下午
 **/
public class Test {
    public static void main(String[] args) {
        Test test = new Test(new int[]{12,33,4,56,22,2,34,33,22,12,34,56});
        System.out.println(test.query(1, 2, 4));
    }

    private final int[] arr;
    private final Map<Integer, List<Integer>> valueIndexListMap;

    public Test(int[] arr) {
        this.arr = arr;
        valueIndexListMap = new HashMap<>();
        for (int i = 0; i < arr.length; i++) {
            if (valueIndexListMap.containsKey(arr[i])) {
                valueIndexListMap.get(arr[i]).add(i);
            } else {
                valueIndexListMap.put(arr[i], new ArrayList<>());
                valueIndexListMap.get(arr[i]).add(i);
            }
        }
    }

    public int query(int left, int right, int value) {
        List<Integer> indexList = valueIndexListMap.get(value);
        if (null == indexList) {
            return 0;
        }
        int ans = this.lowerNum(indexList, left) - this.lowerNum(indexList, right);
        if (arr[right] == value) {
            ans++;
        }
        return ans;
    }

    private int lowerNum(List<Integer> indexList, int target) {
        int L = 0;
        int R = indexList.size() - 1;
        while ( L <= R) {
            int mid = L + (R - L) / 2;
            if (indexList.get(mid) < target) {
                L = mid + 1;
            } else {
                R = mid - 1;
            }
        }
        return L;
    }
}
